package com.simpleframe.views.components;

import java.io.Writer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.simpleframe.util.Utils;

public class FieldError extends Component {
	
	protected String name;
	protected String message;
		
	protected Map<String, List<String>> fieldErrors;
	
	@Override
	public boolean end(Writer writer, String tagBody) {
		evaluateParameters();
		mergeTemplate(writer,getTemplate());
		return false;
	}
	
	protected void evaluateParameters(){
		if(name!=null){
			addParameter("name", name);
		}

		message = getFieldErrorMessage(name);
		if(message!=null){
			addParameter("message", message);
		}
		
	}
	
	private String getFieldErrorMessage(String name){
		if(Utils.isNotNull(fieldErrors)){
			if(fieldErrors.containsKey(name)){
				List<String> list = fieldErrors.get(name);
				return constructMessage(list);
			}
		}
		return "";
	}
	
	private String constructMessage(List<String> list){
		StringBuffer html = new StringBuffer();
		if(list!=null){
			for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
				String string =  iterator.next();
				html.append(string+" ");
			}
		}
		return html.toString();
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public void setFieldErrors(Map<String, List<String>> fieldErrors) {
		this.fieldErrors = fieldErrors;
	}

}
